package com.zzh.zzhaiagent.configure;

import com.zzh.zzhaiagent.filter.TokenAILoveAgentFilter;
import com.zzh.zzhaiagent.filter.TokenAuthenticationFilter;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author: zzh
 * @date: 2025/05/26 20:21:40
 * @version: 1.0
 */
//配置跨域 + 拦截器
@Configuration
@Order(2)
public class CorsWebConfig implements WebMvcConfigurer {

    @Resource
    private TokenAILoveAgentFilter tokenAILoveAgentFilter;

    @Resource
    private TokenAuthenticationFilter tokenAuthenticationFilter;

    //注册拦截器 order 值越小，优先级越高
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //先执行TokenAuthenticationFilter，再执行TokenAILoveAgentFilter


        registry.addInterceptor(tokenAuthenticationFilter)
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/code/**","/api/userProfiles/login/**","/api/userProfiles/refresh","/api/ip/test")
                .order(1);//只拦截所有 /api/** 开头的请求 排除 /api/code/** /api/userProfiles/login/** /api/userProfiles/refresh 开头的请求

        registry.addInterceptor(tokenAILoveAgentFilter)
                .addPathPatterns("/api/ai/**")
                .excludePathPatterns("/api/userProfiles/login/**","/api/userProfiles/refresh","/api/code/**")
                .order(2);//只拦截所有 /api/ai/** 开头的请求 排除 /api/userProfiles/login/** /api/userProfiles/refresh /api/code/** 开头的请求
    }

    //配置跨域
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //覆盖所有请求
        registry.addMapping("/**")
                //允许发送Cookie
                .allowCredentials(true)
                //允许跨域请求的域名
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                //允许跨域请求的请求头
                .allowedHeaders("*");
    }

}
